<?php

$_POST['to'] = htmlescape(trim($_POST['to']));
$_POST['type'] = htmlescape(trim($_POST['type']));

require_once('init.php');

$nodes = new Nodes();

$result   = false;
$from     = $nodes->getNode($_POST['from_id']);
$linkType = $nodes->getNode($_POST['type_id']);
$to       = $nodes->getNode($_POST['to_id']);

if ( ! $from->getId() ) {
	die('Wrong from id');
}

if ( ! $linkType->getId() && trim($_POST['type'] ) {
	$linkType = $nodes->autoNode($_POST['type']);
}

if ( ! $to->getId() && $_POST['to'] ) {
	$to = $nodes->autoNode($_POST['to']);
}

if ($from->getId() && $linkType->getId() && $to->getId()) {
	$result = $from->addLink($linkType->getId(), $to->getId());
} else {
    die('Wrong texts and ids');
}

if ($result) {
    redirect(geturl($from->getName(),$from->getId()));
} else {
    die('Failed to add link');
}